package com.zbkj.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zbkj.client.feign.PythonAgentClient;
import com.zbkj.client.service.DialogMemberService;
import com.zbkj.client.service.DialogService;
import com.zbkj.client.service.MessageService;
import com.zbkj.common.model.client.agent.Agent;
import com.zbkj.common.model.client.agent.AgentGroup;
import com.zbkj.common.model.client.agent.ContentCreate;
import com.zbkj.common.response.ClientLoginResponse;
import com.zbkj.common.result.CommonResult;
import com.zbkj.common.request.client.SendMessageRequest;
import com.zbkj.client.config.ClientTokenComponent;
import com.zbkj.common.response.client.DialogListResponse;
import com.zbkj.common.vo.client.LastMessageInfoVo;
import com.zbkj.common.model.client.message.Dialog;
import com.zbkj.common.model.client.message.DialogMember;
import com.zbkj.common.model.client.message.Message;
import com.zbkj.common.response.client.MessageList;
import com.zbkj.common.request.client.MessageListRequest;
import com.zbkj.service.service.AgentGroupService;
import com.zbkj.service.service.AgentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import com.zbkj.common.request.client.AgentSessionAddRequest;
import com.zbkj.common.model.client.message.AgentSession;
import com.zbkj.service.service.AgentSessionService;
import org.springframework.beans.factory.annotation.Qualifier;

@Slf4j
@RestController
@RequestMapping("/api/client/message")
@Api(tags = "消息控制器")
public class MessageController {
    @Autowired
    private DialogService dialogService;
    @Autowired
    private DialogMemberService dialogMemberService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ClientTokenComponent clientTokenComponent;
    @Autowired
    private AgentSessionService agentSessionService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentGroupService agentGroupService;


    // 发送消息（流式输出）
    @ApiOperation(value = "发送消息（流式输出）")
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestBody SendMessageRequest request, HttpServletResponse response, HttpServletRequest httpRequest) throws Exception {
        // 获取userId
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);
        messageService.sendMessage(request, response, httpRequest, userId);
    }

    @ApiOperation(value = "对话框的消息列表")
    @GetMapping("/getMessageList")
    public CommonResult<IPage<Message>> getMessageList(
                    @RequestParam("dialogId") Integer dialogId,
                    @RequestParam("agentSessionId") String agentSessionId,
                    @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                    @RequestParam(value = "pagesize", required = false, defaultValue = "10") Integer pageSize,
                    HttpServletRequest httpRequest) {

        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Page<Message> pageParam = new Page<>(page, pageSize);
        QueryWrapper<Message> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
//                .eq("user_id", userId)
                .eq("dialog_id", dialogId)
                .eq("agent_session_id", agentSessionId)
                .orderByDesc("create_time");

        IPage<Message> result = messageService.page(pageParam, wrapper);

        // 反序返回 result 的记录
        List<Message> records = result.getRecords();
        Collections.reverse(records);
        result.setRecords(records);

        return CommonResult.success(result);
    }

    // 对话框列表
    @ApiOperation(value = "对话框列表")
    @GetMapping("/getDialogList")
    public CommonResult<List<DialogListResponse>> getDialogList(HttpServletRequest request) {
        Integer userId = clientTokenComponent.getLoginUser(request);

        List<DialogListResponse> result = dialogService.getDialogList(userId);
        return CommonResult.success(result);
    }

    /**
     * 生成对话框
     * @param request
     * @param httpRequest
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "生成对话框")
    @PostMapping("/addDialog")
    public CommonResult<Dialog> addDialog(@RequestBody SendMessageRequest request, HttpServletRequest httpRequest) throws Exception {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Dialog dialog = messageService.insertDialog(request,userId);
        return CommonResult.success(dialog);
    }

    /**
     * 置顶对话框
     * @param params
     * @param httpRequest
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "置顶对话框")
    @PostMapping("/topDialog")
    public CommonResult<String> topDialog(@RequestBody Map<String, Object> params, HttpServletRequest httpRequest) throws Exception {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        Integer dialogId = (Integer)params.get("dialogId");
        Integer isTop = (Integer)params.get("isTop");

        Dialog dialog = dialogService.getById(dialogId);
        dialog.setIsTop(isTop);

        boolean result = dialogService.updateById(dialog);
        if (result) {
            return CommonResult.success("置顶成功");
        }

        return CommonResult.failed("置顶失败");
    }

    // 删除对话框
    @ApiOperation(value = "根据sessionId删除对话框的历史对话")
    @PostMapping("/delDialogSession")
    public CommonResult<?> delDialogSession(@RequestBody SendMessageRequest request) {

        messageService.delAgentSession(request);

        return CommonResult.success("删除成功");
    }


    /**
     * 创建会话
     *   -如果没有传dialogId，则是新的聊天窗口，则先创建聊天对话框-》再调用api创建会话-》插入表
     *   -如果有dialogId，说明不是新的会话，则直接用api创建会话-》插入表
     * @param request
     * @param httpRequest
     * @return
     */
    @ApiOperation(value = "创建会话")
    @PostMapping("/createAgentSession")
    public CommonResult<AgentSession> createAgentSession(@RequestBody SendMessageRequest request, HttpServletRequest httpRequest) {
        Integer userId = clientTokenComponent.getLoginUser(httpRequest);

        AgentSession session = messageService.createSession(request,userId);
        return CommonResult.success(session);
    }

    @ApiOperation(value = "对话框的消息列表")
    @GetMapping("/getSessionList")
    public CommonResult<IPage<AgentSession>> getSessionList(
            @RequestParam("dialogId") Integer dialogId,
            @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
            @RequestParam(value = "pagesize", required = false, defaultValue = "10") Integer pageSize,
            HttpServletRequest httpRequest) {

        Page<AgentSession> pageParam = new Page<>(page, pageSize);
        QueryWrapper<AgentSession> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", 0)
                .eq("dialog_id", dialogId)
                .orderByDesc("create_time");

        IPage<AgentSession> result = agentSessionService.page(pageParam, wrapper);

        return CommonResult.success(result);
    }

    /**
     * 获取对话框所有成员的头像以及agent名称
     * @param dialogId
     * @param httpRequest
     * @return
     */
    @ApiOperation(value = "获取对话框所有成员的头像")
    @GetMapping("/getDialogHeadImg")
    public CommonResult<Map<String, Object>> getDialogHeadImg(@RequestParam("dialogId") Integer dialogId,
                                                       HttpServletRequest httpRequest) {

        String token = httpRequest.getHeader("token");
        Map<String, Object> session = messageService.getDialogImgs(dialogId, token);

        return CommonResult.success(session);
    }
} 